<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="1000px" align-center
    :before-close="handleCancel"
    top="5vh"
    class="location-dialog"
  >
    <div class="location-manage-container">
      <!-- 智能搜索框 -->
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          :placeholder="searchPlaceholder"
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
          size="large"
          class="search-input"
          style="font-size: 15px;"
        >
          <template #append>
            <el-button 
              @click="showSearchTips = !showSearchTips"
              :type="showSearchTips ? 'primary' : 'info'"
              size="large"
              title="点击查看搜索提示"
              class="search-tip-button"
            >
              <el-icon><Pointer /></el-icon>
            </el-button>
          </template>
        </el-input>
        
        <!-- 搜索建议 -->
        <div v-if="searchSuggestions.length > 0 && searchKeyword.length > 0" class="search-suggestions" style="margin-top: 8px;">
          <div class="suggestion-header" style="font-size: 12px; color: #666; margin-bottom: 4px;">搜索建议：</div>
          <el-tag
            v-for="suggestion in searchSuggestions.slice(0, 5)"
            :key="suggestion"
            size="medium"
            @click="selectSuggestion(suggestion)"
            class="suggestion-tag"
            style="margin-right: 8px; margin-bottom: 6px; cursor: pointer; font-size: 13px;"
          >
            {{ suggestion }}
          </el-tag>
        </div>
        
        <!-- 搜索提示面板 -->
        <el-collapse-transition>
          <div v-if="showSearchTips" class="search-tips" style="background: #f5f7fa; padding: 12px; border-radius: 4px; margin-top: 8px;">
            <div class="tips-header" style="font-weight: bold; margin-bottom: 8px;">提示：</div>
            <ul class="tips-list" style="margin: 0; padding-left: 20px; font-size: 12px; color: #666;">
              <li><strong>精确搜索：</strong>输入完整名称，如 "A栋办公楼"</li>
              <li><strong>模糊搜索：</strong>输入部分关键词，如 "会议" 查找所有会议室</li>
              <li><strong>房间搜索：</strong>输入房间名称，如 "101会议室" 或 "办公室"</li>
              <li><strong>楼层搜索：</strong>输入 "1楼" 或 "2楼" 查找楼层</li>
              <li><strong>建筑搜索：</strong>输入建筑名称，如 "A栋" 或 "办公楼"</li>
            </ul>
          </div>
        </el-collapse-transition>
        
        <!-- 搜索统计 -->
        <div v-if="searchKeyword.length > 0" class="search-stats" style="margin-top: 8px; font-size: 12px; color: #666;">
          找到 <span class="stats-number" style="color: #409eff; font-weight: bold;">{{ searchResultCount }}</span> 个匹配项
          <span v-if="searchResultCount > 0" class="stats-detail">
            ({{ searchResultTypes.join('、') }})
          </span>
        </div>
              
        <!-- 租户信息和数据状态 -->
        <div class="tenant-info-section" style="margin-top: 16px;">
          <div class="info-card">
            <div class="info-row">
              <span class="info-label">租户ID:</span>
              <span class="info-value" v-if="currentTenantId">
                <el-tag type="primary" size="small">{{ currentTenantId }}</el-tag>
              </span>
              <span class="info-value" v-else>
                <el-tag type="info" size="small">未设置</el-tag>
              </span>
            </div>
                  
            <div class="info-row">
              <span class="info-label">数据状态:</span>
              <span class="info-value">
                <el-tag 
                  :type="fullLocationTree.length > 0 ? 'success' : 'warning'" 
                  size="small"
                >
                  {{ fullLocationTree.length > 0 ? `${fullLocationTree.length} 个根节点` : '无数据' }}
                </el-tag>
              </span>
            </div>
                  
            <div class="info-row">
              <el-button 
                type="text" 
                size="small" 
                @click="refreshLocationData"
                :loading="loading"
                style="padding: 0; margin-left: auto;"
              >
                <el-icon style="margin-right: 4px;"><Refresh /></el-icon>
                刷新数据
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 树形控件 -->
      <div v-loading="loading" element-loading-text="正在加载地点位置数据...">
        <!-- 有数据时的快速操作区域 -->
        <div v-if="filteredLocationTree.length > 0" class="quick-actions" style="margin: 16px 0 12px 0; padding: 12px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #409eff;">
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <div style="font-size: 14px; color: #606266; font-weight: 500;">
              <el-icon style="margin-right: 6px; color: #409eff;"><OfficeBuilding /></el-icon>
              快速操作
            </div>
            <el-button 
              type="primary"
              size="small"
              @click="handleAddRoot"
              style="font-size: 12px;"
            >
              <el-icon style="margin-right: 4px;"><Plus /></el-icon>
              添加新建筑
            </el-button>
          </div>
        </div>
        
        <!-- 有数据时显示树形控件 -->
        <el-tree
          v-if="filteredLocationTree.length > 0"
          ref="treeRef"
          :data="filteredLocationTree"
          :props="{ children: 'children', label: 'name' }"
          node-key="id"
          :show-checkbox="false"
          :default-expand-all="false"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          class="location-tree"
          style="margin-top: 16px; font-size: 14px;"
        >
        <template #default="{ node, data }">
          <div class="tree-node">
            <span class="node-icon">
              <i v-if="data.type === 'building'" class="el-icon-office-building" style="color: #409eff;"></i>
              <i v-else-if="data.type === 'floor'" class="el-icon-menu" style="color: #67c23a;"></i>
              <i v-else-if="data.type === 'room'" class="el-icon-house" style="color: #e6a23c;"></i>
              <i v-else-if="data.type === 'electricmeter'" class="el-icon-lightning" style="color: #f56c6c;"></i>
              <i v-else-if="data.type === 'watermeter'" class="el-icon-drizzling" style="color: #409eff;"></i>
            </span>
            <span class="node-label">{{ data.name }}</span>
            <span class="node-type">[{{ getTypeLabel(data.type) }}]</span>
            
            <!-- 管理模式下的操作按钮 -->
            <div class="node-actions" style="margin-left: auto;">
              <el-button size="mini" type="info" @click.stop="handleViewDetail(data)" title="查看详情">
                <el-icon><View /></el-icon>
              </el-button>
              
              <el-button size="mini" type="primary" @click.stop="handleEdit(data)" title="编辑">
                <el-icon><Edit /></el-icon>
              </el-button>
              
              <!-- 添加按钮组 -->
              <el-dropdown @command="handleAddCommand" trigger="click" @click.stop>
                <el-button size="mini" type="success" title="添加">
                  <el-icon><Plus /></el-icon>
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <!-- 添加同级 -->
                    <el-dropdown-item 
                      :command="{action: 'addSibling', node: data}"
                      :disabled="!data.parentId && data.type === 'building'"
                    >
                      <el-icon style="margin-right: 6px;"><Plus /></el-icon>
                      添加同级{{ getTypeLabel(data.type) }}
                    </el-dropdown-item>
                    
                    <!-- 添加子级 -->
                    <el-dropdown-item 
                      v-if="data.type !== 'room'"
                      :command="{action: 'addChild', node: data}"
                    >
                      <el-icon style="margin-right: 6px; color: #67c23a;"><FolderAdd /></el-icon>
                      添加{{ getChildTypeLabel(data.type) }}
                    </el-dropdown-item>
                    
                    <!-- 添加根级建筑 (只在顶级显示) -->
                    <el-dropdown-item 
                      v-if="!data.parentId"
                      :command="{action: 'addRoot', node: data}"
                      divided
                    >
                      <el-icon style="margin-right: 6px; color: #409eff;"><OfficeBuilding /></el-icon>
                      添加新建筑
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              
              <el-button 
                size="mini" 
                type="danger" 
                @click.stop="handleDelete(data)" 
                :title="getDeleteTooltip(data)"
                :loading="loading && deletingNodeId === data.id"
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>
      
      <!-- 无数据时的空状态显示 -->
      <div v-else-if="!loading && currentTenantId" class="empty-state" style="margin-top: 16px; text-align: center; padding: 60px 20px; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); border-radius: 12px; border: 1px solid #e4e7ed;">
        <div class="empty-icon" style="margin-bottom: 20px;">
          <el-icon size="64" style="color: #409eff;"><OfficeBuilding /></el-icon>
        </div>
        <div class="empty-title" style="font-size: 18px; color: #303133; margin-bottom: 12px; font-weight: 600;">
          暂无地点位置数据
        </div>
        <div class="empty-description" style="font-size: 14px; color: #606266; margin-bottom: 24px; line-height: 1.6;">
          <div style="margin-bottom: 4px;">当前租户下还没有创建任何地点位置</div>
          <div>您可以点击下方按钮开始创建第一个建筑</div>
        </div>
        
        <!-- 管理模式下显示创建按钮 -->
        <div class="empty-actions">
          <el-button 
            type="primary"
            size="large"
            @click="handleAddRoot"
            style="min-width: 200px; height: 48px; font-size: 16px; font-weight: 500;"
          >
            <el-icon style="margin-right: 8px; font-size: 18px;"><OfficeBuilding /></el-icon>
            创建第一个建筑
          </el-button>
          <div style="margin-top: 16px; font-size: 13px; color: #909399; background: rgba(255,255,255,0.8); padding: 8px 16px; border-radius: 6px; display: inline-block;">
            💡 建议先创建建筑，再添加楼层和房间
          </div>
        </div>
      </div>
      
      <!-- 租户ID缺失时的提示 -->
      <div v-else-if="!loading && !currentTenantId" class="no-tenant-state" style="margin-top: 16px; text-align: center; padding: 60px 20px; background: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%); border-radius: 12px; border: 1px solid #fdcb6e;">
        <div class="empty-icon" style="margin-bottom: 20px;">
          <el-icon size="64" style="color: #e17055;"><QuestionFilled /></el-icon>
        </div>
        <div class="empty-title" style="font-size: 18px; color: #2d3436; margin-bottom: 12px; font-weight: 600;">
          缺少租户信息
        </div>
        <div class="empty-description" style="font-size: 14px; color: #636e72; margin-bottom: 20px; background: rgba(255,255,255,0.8); padding: 12px 20px; border-radius: 8px; display: inline-block;">
          无法加载地点位置数据，请确保已正确设置租户ID
        </div>
      </div>
      </div>

      <!-- 底部按钮 -->
      <div class="dialog-footer">
        <el-button size="large" @click="handleCancel">关闭</el-button>
      </div>
    </div>
  </el-dialog>
  
  <!-- 地点位置详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="地点位置详情"
    width="600px" align-center
    :before-close="closeDetailDialog"
    top="10vh"
    class="detail-dialog"
  >
    <div v-loading="detailLoading" element-loading-text="正在获取详细信息...">
      <div v-if="currentLocationDetail" class="detail-content">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3 class="section-title">
            <el-icon class="title-icon"><OfficeBuilding /></el-icon>
            基本信息
          </h3>
          <div class="detail-grid">
            <div class="detail-item">
              <label>位置名称：</label>
              <span class="detail-value primary">{{ currentLocationDetail.name }}</span>
            </div>
            <div class="detail-item">
              <label>位置类型：</label>
              <el-tag 
                :type="getLocationTypeTagType(currentLocationDetail.locationType || '')"
                class="detail-tag"
              >
                {{ getTypeLabel(currentLocationDetail.locationType || '') }}
              </el-tag>
            </div>
            <div class="detail-item">
              <label>位置ID：</label>
              <span class="detail-value">{{ currentLocationDetail.id }}</span>
            </div>
            <div class="detail-item">
              <label>排序序号：</label>
              <span class="detail-value">{{ currentLocationDetail.orderNum || '未设置' }}</span>
            </div>
            <div class="detail-item" v-if="currentLocationDetail.parentId">
              <label>父位置ID：</label>
              <span class="detail-value">{{ currentLocationDetail.parentId }}</span>
            </div>
            <div class="detail-item" v-if="currentLocationDetail.tenantId">
              <label>租户ID：</label>
              <span class="detail-value">{{ currentLocationDetail.tenantId }}</span>
            </div>
          </div>
        </div>
        
        <!-- 子位置信息 -->
        <div v-if="currentLocationDetail.children && currentLocationDetail.children.length > 0" class="detail-section">
          <h3 class="section-title">
            <el-icon class="title-icon"><Grid /></el-icon>
            子位置列表 ({{ currentLocationDetail.children.length }})
          </h3>
          <div class="children-list">
            <div 
              v-for="child in currentLocationDetail.children" 
              :key="child.id"
              class="child-item"
            >
              <div class="child-info">
                <span class="child-icon">
                  <i v-if="child.locationType === 'building'" class="el-icon-office-building" style="color: #409eff;"></i>
                  <i v-else-if="child.locationType === 'floor'" class="el-icon-menu" style="color: #67c23a;"></i>
                  <i v-else-if="child.locationType === 'room'" class="el-icon-house" style="color: #e6a23c;"></i>
                </span>
                <span class="child-name">{{ child.name }}</span>
                <el-tag size="small" class="child-type-tag">
                  {{ getTypeLabel(child.locationType || '') }}
                </el-tag>
              </div>
              <div class="child-actions">
                <el-button 
                  size="mini" 
                  type="text" 
                  @click="handleViewDetail({ id: child.id, name: child.name, type: child.locationType || '' } as LocationTreeNode)"
                >
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="no-children">
          <el-empty description="该位置下暂无子位置" :image-size="80" />
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="detail-dialog-footer">
        <el-button @click="closeDetailDialog">关闭</el-button>
        <el-button 
          v-if="currentLocationDetail" 
          type="primary" 
          @click="handleEdit({
            id: currentLocationDetail.id,
            name: currentLocationDetail.name,
            type: currentLocationDetail.locationType || '',
            children: currentLocationDetail.children
          } as LocationTreeNode); closeDetailDialog()"
        >
          编辑信息
        </el-button>
      </div>
    </template>
  </el-dialog>
  
  <!-- 地点位置编辑对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑地点位置"
    width="500px" align-center
    :before-close="handleCancelEdit"
    top="10vh"
    class="edit-dialog"
  >
    <div v-loading="editLoading" element-loading-text="正在保存...">
      <el-form 
        ref="editFormRef"
        :model="editFormData"
        :rules="editFormRules"
        label-width="120px"
        class="edit-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h4 class="section-title">基本信息</h4>
          
          <el-form-item label="位置名称" prop="name">
            <el-input
              v-model="editFormData.name"
              placeholder="请输入地点位置名称"
              maxlength="50"
              show-word-limit
              clearable
            />
          </el-form-item>
          
          <el-form-item label="位置类型" prop="locationType">
            <el-select 
              v-model="editFormData.locationType" 
              placeholder="请选择位置类型"
              style="width: 100%;"
            >
              <el-option label="建筑" value="building" />
              <el-option label="楼层" value="floor" />
              <el-option label="房间" value="room" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="排序序号" prop="orderNum">
            <el-input-number
              v-model="editFormData.orderNum"
              :min="0"
              :max="9999"
              placeholder="请输入排序序号"
              style="width: 100%;"
            />
          </el-form-item>
        </div>
        
        <!-- 关系信息 -->
        <div class="form-section">
          <h4 class="section-title">关系信息</h4>
          
          <el-form-item label="父位置ID">
            <el-input
              :model-value="editFormData.parentId ? String(editFormData.parentId) : '无上级'"
              readonly
              placeholder="系统自动维护"
            />
            <div class="form-tip">父位置关系由系统自动维护，不可修改</div>
          </el-form-item>
          
          <el-form-item label="租户ID">
            <el-input
              :model-value="editFormData.tenantId ? String(editFormData.tenantId) : '未设置'"
              readonly
              placeholder="系统自动维护"
            />
            <div class="form-tip">租户信息由系统自动维护，不可修改</div>
          </el-form-item>
          
          <el-form-item label="位置ID">
            <el-input
              :model-value="editFormData.id ? String(editFormData.id) : '未分配'"
              readonly
              placeholder="系统自动维护"
            />
            <div class="form-tip">位置ID由系统自动分配，不可修改</div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    
    <template #footer>
      <div class="edit-dialog-footer">
        <el-button @click="handleCancelEdit" :disabled="editLoading">
          取消
        </el-button>
        <el-button 
          type="primary" 
          @click="handleSaveEdit"
          :loading="editLoading"
        >
          保存修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, defineExpose, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Edit,
  Delete,
  Search,
  QuestionFilled,
  OfficeBuilding,
  Grid,
  House,
  Pointer,
  ArrowDown,
  FolderAdd,
  View,
  Refresh
} from '@element-plus/icons-vue'
import { 
  addLocation, 
  getLocationTree, 
  editLocation, 
  deleteLocation,
  getLocationDetail 
} from '@/api/settle'
import { 
  MrsLocationAddRequest, 
  MrsLocation, 
  LocationTreeNode, 
  LocationType,
  LocationTypeLabels 
} from '@/api/types/location'

// 组件属性
interface Props {
  mode?: 'manage' | 'select' // 添加模式属性：管理模式或选择模式
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'manage'
})

const emit = defineEmits(['confirm', 'select'])

// 响应式数据
const dialogVisible = ref(false)
const mode = ref<'manage' | 'select'>(props.mode)
const treeRef = ref()
const searchKeyword = ref('')
const showSearchTips = ref(false)
const loading = ref(false)
const currentTenantId = ref<number | undefined>()
const deletingNodeId = ref<string | number | null>(null) // 正在删除的节点ID


// 编辑相关状态
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormData = ref<MrsLocation>({})
const editFormRef = ref()

// 编辑表单规则
const editFormRules = {
  name: [
    { required: true, message: '请输入地点位置名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度应在1-50个字符之间', trigger: 'blur' }
  ],
  locationType: [
    { required: true, message: '请选择位置类型', trigger: 'change' }
  ],
  orderNum: [
    { type: 'number', message: '排序序号必须是数字', trigger: 'blur' }
  ]
}

// 详情查看相关状态
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const currentLocationDetail = ref<MrsLocation | null>(null)

// 地点位置数据
const fullLocationTree = ref<LocationTreeNode[]>([])
// 地点位置数据
const locationTreeData = ref<LocationTreeNode[]>([])

// 加载API数据
const loadLocationData = async () => {
  try {
    loading.value = true
    
    if (!currentTenantId.value) {
      ElMessage.error('缺少租户信息，无法加载地点位置数据')
      fullLocationTree.value = []
      return
    }
    
    const res = await getLocationTree(currentTenantId.value)
    
    if ((res.code === 0 || res.code === 200) && res.data) {
      fullLocationTree.value = convertLocationDataToTreeNodes(res.data)
    } else {
      const errorMsg = res.msg || res.message || '加载地点位置数据失败'
      ElMessage.error(`加载失败: ${errorMsg}`)
      fullLocationTree.value = []
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请检查网络连接后重试')
    fullLocationTree.value = []
  } finally {
    loading.value = false
  }
}

// 转换后端数据为前端树节点格式
const convertLocationDataToTreeNodes = (locations: LocationTreeNode[]): LocationTreeNode[] => {
  return locations.map(location => {
    const treeNode: LocationTreeNode = {
      id: location.id,
      name: location.name || '',
      type: location.locationType || location.type || 'room',
      locationType: location.locationType,
      parentId: location.parentId,
      tenantId: location.tenantId,
      orderNum: location.orderNum
    }
    
    if (location.children && location.children.length > 0) {
      treeNode.children = convertLocationDataToTreeNodes(location.children)
    }
    
    return treeNode
  })
}



// 计算属性
const dialogTitle = computed(() => '地点位置管理')

const searchPlaceholder = computed(() => {
  return '搜索位置名称...'
})

// 搜索建议
const searchSuggestions = computed(() => {
  if (!searchKeyword.value || searchKeyword.value.length < 1) return []
  
  const suggestions: string[] = []
  const keyword = searchKeyword.value.toLowerCase()
  
  // 收集所有节点名称
  const collectNames = (nodes: LocationTreeNode[]) => {
    nodes.forEach(node => {
      if (node.name.toLowerCase().includes(keyword)) {
        suggestions.push(node.name)
      }
      if (node.children) {
        collectNames(node.children)
      }
    })
  }
  
  collectNames(fullLocationTree.value)
  return [...new Set(suggestions)] // 去重
})

// 搜索结果统计
const searchResultCount = computed(() => {
  if (!searchKeyword.value) return 0
  
  let count = 0
  const countNodes = (nodes: LocationTreeNode[]) => {
    nodes.forEach(node => {
      if (node.name.toLowerCase().includes(searchKeyword.value.toLowerCase())) {
        count++
      }
      if (node.children) {
        countNodes(node.children)
      }
    })
  }
  
  countNodes(filteredLocationTree.value)
  return count
})

const searchResultTypes = computed(() => {
  if (!searchKeyword.value) return []
  
  const types = new Set<string>()
  const collectTypes = (nodes: LocationTreeNode[]) => {
    nodes.forEach(node => {
      if (node.name.toLowerCase().includes(searchKeyword.value.toLowerCase())) {
        types.add(getTypeLabel(node.type))
      }
      if (node.children) {
        collectTypes(node.children)
      }
    })
  }
  
  collectTypes(filteredLocationTree.value)
  return Array.from(types)
})

// 过滤后的树数据（支持搜索）
const filteredLocationTree = computed(() => {
  let result = fullLocationTree.value
  
  // 如果有搜索关键词，进行搜索过滤
  if (searchKeyword.value.trim()) {
    result = searchFilterTree(result)
  }
  
  return result
})

// 搜索过滤函数
const searchFilterTree = (nodes: LocationTreeNode[]): LocationTreeNode[] => {
  return nodes
    .map(node => {
      const filteredNode = { ...node }
      
      if (node.children) {
        const filteredChildren = searchFilterTree(node.children)
        if (filteredChildren.length > 0) {
          filteredNode.children = filteredChildren
        } else {
          delete filteredNode.children
        }
      }
      
      return filteredNode
    })
    .filter(node => {
      // 检查当前节点是否匹配搜索关键词
      const matchesSearch = node.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
      
      // 检查子节点是否有匹配的
      const hasMatchingChildren = node.children && node.children.length > 0
      
      return matchesSearch || hasMatchingChildren
    })
}



// 获取类型标签
const getTypeLabel = (type: string) => {
  return LocationTypeLabels[type as LocationType] || '未知'
}

// 获取子类型标签
const getChildTypeLabel = (parentType: string) => {
  switch (parentType) {
    case 'building': return '楼层'
    case 'floor': return '房间'
    case 'room': return '设备'
    default: return '子项'
  }
}

// 获取删除按钮的提示信息
const getDeleteTooltip = (node: LocationTreeNode) => {
  const hasChildren = node.children && node.children.length > 0
  if (hasChildren) {
    const childCount = node.children!.length
    return `删除 "${node.name}" 及其 ${childCount} 个子项`
  }
  return `删除 "${node.name}"`
}

// 获取位置类型标签的颜色类型
const getLocationTypeTagType = (locationType: string) => {
  switch (locationType) {
    case 'building': return 'primary'
    case 'floor': return 'success' 
    case 'room': return 'warning'
    default: return 'info'
  }
}

// 获取父类型标签
const getParentTypeLabel = (childType: string) => {
  switch (childType) {
    case 'floor': return '建筑'
    case 'room': return '楼层'
    case 'electricmeter':
    case 'watermeter': return '房间'
    default: return '上级'
  }
}

// 处理添加命令
const handleAddCommand = (command: {action: string, node: LocationTreeNode}) => {
  const { action, node } = command
  
  switch (action) {
    case 'addSibling':
      handleAddSibling(node)
      break
    case 'addChild':
      handleAdd(node)
      break
    case 'addRoot':
      handleAddRoot()
      break
  }
}

// 添加同级节点
const handleAddSibling = (node: LocationTreeNode) => {
  // 使用简单的输入框对话框
  ElMessageBox.prompt(`请输入新${getTypeLabel(node.type)}的名称`, `添加同级${getTypeLabel(node.type)}`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S+/,
    inputErrorMessage: '名称不能为空'
  }).then(({ value }) => {
    // 用户输入了名称，再询问排序序号
    ElMessageBox.prompt('请输入排序序号（可选，默认为500）', `添加同级${getTypeLabel(node.type)}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'number',
      inputValue: '500'
    }).then(({ value: orderValue }) => {
      // 调用添加方法，传递节点名称和排序序号
      const orderNum = orderValue ? parseInt(orderValue) : 500;
      addSiblingNode(node, value, orderNum);
    }).catch(() => {
      // 用户取消了排序序号输入，使用默认值
      addSiblingNode(node, value, 500);
    });
  }).catch(() => {
    // 用户取消操作
  });
}

// 添加根级建筑
const handleAddRoot = () => {
  // 使用简单的输入框对话框
  ElMessageBox.prompt('请输入新建筑的名称', '添加新建筑', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S+/,
    inputErrorMessage: '建筑名称不能为空'
  }).then(({ value }) => {
    // 用户输入了建筑名称，再询问排序序号
    ElMessageBox.prompt('请输入排序序号（可选，默认为1000）', '添加新建筑', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'number',
      inputValue: '1000'
    }).then(({ value: orderValue }) => {
      // 调用添加方法，传递建筑名称和排序序号
      const orderNum = orderValue ? parseInt(orderValue) : 1000;
      addRootBuilding(value, orderNum);
    }).catch(() => {
      // 用户取消了排序序号输入，使用默认值
      addRootBuilding(value, 1000);
    });
  }).catch(() => {
    // 用户取消操作
  });
}

// 添加根级建筑
const addRootBuilding = async (buildingName: string, orderNum?: number) => {
  try {
    loading.value = true
    
    const finalOrderNum = (() => {
      if (typeof orderNum === 'number' && !isNaN(orderNum) && orderNum >= 0) {
        return orderNum;
      }
      
      const rootBuildings = fullLocationTree.value.filter(node => node.type === 'building')
      if (rootBuildings.length > 0) {
        const maxOrder = Math.max(...rootBuildings.map(building => {
          const order = building.orderNum || 0
          return typeof order === 'number' && !isNaN(order) ? order : 0
        }))
        return maxOrder + 10
      }
      return 1000
    })()
    
    const addRequest: any = {
      name: buildingName,
      locationType: 'building',
      parentId: undefined,
      tenantId: currentTenantId.value,
      sortNo: finalOrderNum
    }
    
    const res = await addLocation(addRequest)
    if (res.code === 0 || res.code === 200) {
      ElMessage.success(`添加建筑成功`)
      await loadLocationData()
    } else {
      ElMessage.error(`添加失败: ${res.msg || '未知错误'}`)
    }
  } catch (error) {
    ElMessage.error('添加失败')
  } finally {
    loading.value = false
  }
}

// 添加同级节点时调用API
const addSiblingNode = async (node: LocationTreeNode, siblingName: string, orderNum?: number) => {
  try {
    loading.value = true
    
    const finalOrderNum = (() => {
      if (typeof orderNum === 'number' && !isNaN(orderNum) && orderNum >= 0) {
        return orderNum;
      }
      return Date.now() % 1000 || 500
    })()
    
    const addRequest: any = {
      name: siblingName,
      locationType: node.locationType || node.type,
      parentId: node.parentId,
      tenantId: currentTenantId.value || node.tenantId,
      sortNo: finalOrderNum
    }
    
    const res = await addLocation(addRequest)
    if (res.code === 0 || res.code === 200) {
      ElMessage.success(`添加成功`)
      await loadLocationData()
    } else {
      ElMessage.error(`添加失败: ${res.msg || '未知错误'}`)
    }
  } catch (error) {
    ElMessage.error(`添加失败`)
  } finally {
    loading.value = false
  }
}

// 获取节点路径
const getNodePath = (nodeId: string | number, nodes: LocationTreeNode[] = fullLocationTree.value, path: string[] = []): string => {
  for (const node of nodes) {
    const currentPath = [...path, node.name]
    if (node.id === nodeId) {
      return currentPath.join(' > ')
    }
    if (node.children) {
      const result = getNodePath(nodeId, node.children, currentPath)
      if (result) return result
    }
  }
  return ''
}



// 获取子节点类型
const getChildType = (parentType: string): string | null => {
  switch (parentType) {
    case 'building': return 'floor'
    case 'floor': return 'room'
    default: return null
  }
}

// 更新节点名称时调用API
const updateNodeName = async (nodeId: string | number, newName: string) => {
  try {
    loading.value = true
    
    // 获取详情信息
    const detailRes = await getLocationDetail(typeof nodeId === 'string' ? parseInt(nodeId) : nodeId)
    if (detailRes.code !== 0 || !detailRes.data) {
      throw new Error('获取节点详情失败')
    }
    
    const updateData: MrsLocation = {
      ...detailRes.data,
      name: newName
    }
    
    const res = await editLocation(updateData)
    if (res.code === 0) {
      ElMessage.success(`已成功更新名称为: ${newName}`)
      // 重新加载数据
      await loadLocationData()
    } else {
      ElMessage.error(`更新名称失败: ${res.msg || res.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('更新节点名称失败:', error)
    ElMessage.error('更新名称失败')
  } finally {
    loading.value = false
  }
}

// 添加子节点时调用API
const addChildNode = async (parentNode: LocationTreeNode, childType: string, childName: string, orderNum?: number) => {
  try {
    loading.value = true
    
    const finalOrderNum = (() => {
      if (typeof orderNum === 'number' && !isNaN(orderNum) && orderNum >= 0) {
        return orderNum;
      }
      
      if (parentNode.children && parentNode.children.length > 0) {
        const maxOrder = Math.max(...parentNode.children.map(child => {
          const order = child.orderNum || 0
          return typeof order === 'number' && !isNaN(order) ? order : 0
        }))
        return maxOrder + 1
      }
      return 100
    })()
    
    const addRequest: any = {
      name: childName,
      locationType: childType,
      parentId: typeof parentNode.id === 'string' ? parseInt(parentNode.id) : parentNode.id,
      tenantId: currentTenantId.value || parentNode.tenantId,
      sortNo: finalOrderNum
    }
    
    const res = await addLocation(addRequest)
    if (res.code === 0 || res.code === 200) {
      ElMessage.success(`添加成功`)
      await loadLocationData()
      
      nextTick(() => {
        if (treeRef.value) {
          treeRef.value.setExpanded(parentNode.id, true)
        }
      })
    } else {
      ElMessage.error(`添加失败: ${res.msg || '未知错误'}`)
    }
  } catch (error) {
    ElMessage.error(`添加失败`)
  } finally {
    loading.value = false
  }
}

// 删除节点时调用API
const deleteNode = async (nodeId: string | number, nodeName?: string) => {
  try {
    loading.value = true
    deletingNodeId.value = nodeId // 设置正在删除的节点ID
    
    const numericId = typeof nodeId === 'string' ? parseInt(nodeId) : nodeId
    
    console.log('删除地点位置请求参数:', {
      id: numericId,
      nodeName: nodeName || '未知节点',
      apiPath: `/mrs/location/delete/${numericId}`
    }) // 详细日志记录
    
    const res = await deleteLocation(numericId)
    
    console.log('删除地点位置响应:', res) // 记录响应日志
    
    if (res.code === 0) {
      ElMessage.success({
        message: nodeName ? `已成功删除"${nodeName}"` : '删除成功',
        type: 'success',
        duration: 3000,
        showClose: true
      })
      
      // 重新加载数据
      await loadLocationData()
      
      // 记录成功日志
      console.log(`地点位置删除成功 - ID: ${numericId}, 名称: ${nodeName}`)
      
    } else {
      const errorMsg = res.msg || res.message || '删除操作失败，请稍后重试'
      ElMessage.error({
        message: `删除失败: ${errorMsg}`,
        type: 'error',
        duration: 5000,
        showClose: true
      })
      console.error(`删除地点位置失败 - 错误码: ${res.code}, 错误信息: ${errorMsg}`)
    }
    
  } catch (error) {
    console.error('删除节点网络请求失败:', {
      nodeId,
      nodeName,
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined
    })
    
    ElMessage.error({
      message: '网络请求失败，请检查网络连接后重试',
      type: 'error',
      duration: 5000,
      showClose: true
    })
  } finally {
    loading.value = false
    deletingNodeId.value = null // 清除删除状态
  }
}

// 打开对话框
const openDialog = async (tenantId?: number) => {
  // 参数验证和日志记录
  console.log('打开地点位置管理对话框:', {
    tenantId,
    timestamp: new Date().toISOString()
  })
  
  dialogVisible.value = true
  searchKeyword.value = ''
  showSearchTips.value = false
  
  // 设置当前租户ID
  if (tenantId) {
    currentTenantId.value = tenantId
  } else {
    console.warn('未提供tenantId参数，无法加载数据')
    // 允许不提供租户ID，但会显示特殊提示
    currentTenantId.value = undefined
  }
  
  try {
    // 加载数据
    await loadLocationData()
    
    // 初始化树组件状态
    nextTick(() => {
      // 树形控件已经禁用多选，不需要设置复选框状态
    })
  } catch (error) {
    console.error('打开对话框时加载数据失败:', error)
    ElMessage.error('初始化失败，请重试')
  }
}

const handleSearch = () => {
  // 搜索时自动展开匹配的节点
  nextTick(() => {
    if (treeRef.value && searchKeyword.value) {
      expandMatchingNodes();
    }
  })
}



const selectSuggestion = (suggestion: string) => {
  searchKeyword.value = suggestion
  handleSearch()
}

const expandMatchingNodes = () => {
  if (!treeRef.value) return
  
  const expandNode = (nodes: LocationTreeNode[]) => {
    nodes.forEach(node => {
      if (node.name.toLowerCase().includes(searchKeyword.value.toLowerCase())) {
        treeRef.value.setExpanded(node.id, true)
      }
      if (node.children) {
        expandNode(node.children)
      }
    })
  }
  
  expandNode(filteredLocationTree.value)
}

// 处理节点点击
const handleNodeClick = (data: LocationTreeNode) => {
  if (mode.value === 'select') {
    emit('select', data)
    dialogVisible.value = false
  }
  // 管理模式下的点击只用于展开/折叠
}







const handleCancel = () => {
  dialogVisible.value = false
  searchKeyword.value = ''
  showSearchTips.value = false
}

// 查看节点详情
const handleViewDetail = async (data: LocationTreeNode) => {
  try {
    detailLoading.value = true
    
    const numericId = typeof data.id === 'string' ? parseInt(data.id) : data.id
    
    console.log('获取地点位置详情请求参数:', {
      id: numericId,
      nodeName: data.name,
      apiPath: `/mrs/location/detail/${numericId}`
    }) // 详细日志记录
    
    const res = await getLocationDetail(numericId)
    
    console.log('获取地点位置详情响应:', res) // 记录响应日志
    
    if (res.code === 0 && res.data) {
      currentLocationDetail.value = res.data
      detailDialogVisible.value = true
      
      console.log(`地点位置详情获取成功 - ID: ${numericId}, 名称: ${data.name}`)
    } else {
      const errorMsg = res.msg || res.message || '获取详情失败'
      ElMessage.error({
        message: `无法获取详情: ${errorMsg}`,
        type: 'error',
        duration: 3000,
        showClose: true
      })
      console.error(`获取地点位置详情失败 - 错误码: ${res.code}, 错误信息: ${errorMsg}`)
    }
    
  } catch (error) {
    console.error('获取节点详情网络请求失败:', {
      nodeId: data.id,
      nodeName: data.name,
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined
    })
    
    ElMessage.error({
      message: '网络请求失败，请检查网络连接后重试',
      type: 'error',
      duration: 5000,
      showClose: true
    })
  } finally {
    detailLoading.value = false
  }
}

// 关闭详情对话框
const closeDetailDialog = () => {
  detailDialogVisible.value = false
  currentLocationDetail.value = null
}

// 编辑节点
const handleEdit = async (data: LocationTreeNode) => {
  try {
    editLoading.value = true
    
    // 参数验证
    if (!data.id || !data.name) {
      ElMessage.error('节点数据不完整，无法编辑')
      return
    }
    
    const numericId = typeof data.id === 'string' ? parseInt(data.id) : data.id
    
    console.log('获取编辑节点详情请求参数:', {
      id: numericId,
      nodeName: data.name,
      apiPath: `/mrs/location/detail/${numericId}`
    })
    
    // 获取节点完整信息
    const detailRes = await getLocationDetail(numericId)
    
    console.log('获取编辑节点详情响应:', detailRes)
    
    if (detailRes.code === 0 && detailRes.data) {
      // 初始化编辑表单数据
      editFormData.value = {
        ...detailRes.data,
        // 确保所有必要字段都有值
        name: detailRes.data.name || '',
        locationType: detailRes.data.locationType || '',
        orderNum: detailRes.data.orderNum || 0,
        parentId: detailRes.data.parentId,
        tenantId: detailRes.data.tenantId || currentTenantId.value
      }
      
      // 打开编辑对话框
      editDialogVisible.value = true
      
      console.log(`地点位置编辑对话框已打开 - ID: ${numericId}, 名称: ${data.name}`)
    } else {
      const errorMsg = detailRes.msg || detailRes.message || '获取节点详情失败'
      ElMessage.error({
        message: `无法编辑: ${errorMsg}`,
        type: 'error',
        duration: 3000,
        showClose: true
      })
      console.error(`获取编辑节点详情失败 - 错误码: ${detailRes.code}, 错误信息: ${errorMsg}`)
    }
    
  } catch (error) {
    console.error('编辑节点初始化失败:', {
      nodeId: data.id,
      nodeName: data.name,
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined
    })
    
    ElMessage.error({
      message: '编辑初始化失败，请检查网络连接后重试',
      type: 'error',
      duration: 5000,
      showClose: true
    })
  } finally {
    editLoading.value = false
  }
}

// 保存编辑
const handleSaveEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    // 表单验证
    const isValid = await editFormRef.value.validate()
    if (!isValid) {
      ElMessage.warning('请正确填写所有必填项')
      return
    }
    
    editLoading.value = true
    
    console.log('保存地点位置编辑请求参数:', {
      ...editFormData.value,
      apiPath: '/mrs/location/update'
    })
    
    // 调用更新接口
    const res = await editLocation(editFormData.value)
    
    console.log('保存地点位置编辑响应:', res)
    
    if (res.code === 0) {
      ElMessage.success({
        message: `地点位置"${editFormData.value.name}"编辑成功`,
        type: 'success',
        duration: 3000,
        showClose: true
      })
      
      // 关闭编辑对话框
      editDialogVisible.value = false
      
      // 重新加载数据
      await loadLocationData()
      
      console.log(`地点位置编辑成功 - ID: ${editFormData.value.id}, 名称: ${editFormData.value.name}`)
    } else {
      const errorMsg = res.msg || res.message || '编辑失败，请稍后重试'
      ElMessage.error({
        message: `编辑失败: ${errorMsg}`,
        type: 'error',
        duration: 5000,
        showClose: true
      })
      console.error(`地点位置编辑失败 - 错误码: ${res.code}, 错误信息: ${errorMsg}`)
    }
    
  } catch (error) {
    console.error('保存编辑网络请求失败:', {
      editData: editFormData.value,
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined
    })
    
    ElMessage.error({
      message: '网络请求失败，请检查网络连接后重试',
      type: 'error',
      duration: 5000,
      showClose: true
    })
  } finally {
    editLoading.value = false
  }
}

// 取消编辑
const handleCancelEdit = () => {
  editDialogVisible.value = false
  editFormData.value = {}
  
  // 清理表单验证状态
  if (editFormRef.value) {
    editFormRef.value.clearValidate()
  }
  
  console.log('用户取消编辑操作')
}

// 添加子节点
const handleAdd = (data: LocationTreeNode) => {
  const childType = getChildType(data.type)
  if (!childType) {
    ElMessage.warning(`${getTypeLabel(data.type)}不能添加子项`)
    return
  }
  
  // 使用简单的输入框对话框
  ElMessageBox.prompt(`请输入新${getTypeLabel(childType)}的名称`, `添加${getTypeLabel(childType)}`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S+/,
    inputErrorMessage: '名称不能为空'
  }).then(({ value }) => {
    // 用户输入了名称，再询问排序序号
    ElMessageBox.prompt('请输入排序序号（可选，默认为100）', `添加${getTypeLabel(childType)}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'number',
      inputValue: '100'
    }).then(({ value: orderValue }) => {
      // 调用添加方法，传递父节点、子节点类型、子节点名称和排序序号
      const orderNum = orderValue ? parseInt(orderValue) : 100;
      addChildNode(data, childType, value, orderNum);
    }).catch(() => {
      // 用户取消了排序序号输入，使用默认值
      addChildNode(data, childType, value, 100);
    });
  }).catch(() => {
    // 用户取消操作
  });
}

// 删除节点
const handleDelete = (data: LocationTreeNode) => {
  // 安全检查：防止在加载过程中进行删除操作
  if (loading.value) {
    ElMessage.warning('正在加载中，请稍后再试')
    return
  }
  
  // 检查节点数据的完整性
  if (!data.id || !data.name) {
    ElMessage.error('节点数据不完整，无法执行删除操作')
    console.error('无效的节点数据:', data)
    return
  }
  
  // 检查节点的子项数量
  const hasChildren = data.children && data.children.length > 0
  const childrenCount = hasChildren ? data.children!.length : 0
  
  // 计算所有子孙节点数量（递归统计）
  const countAllDescendants = (node: LocationTreeNode): number => {
    let count = 0
    if (node.children) {
      count += node.children.length
      node.children.forEach(child => {
        count += countAllDescendants(child)
      })
    }
    return count
  }
  
  const totalDescendants = countAllDescendants(data)
  
  // 特殊情况检查：对于数据量很大的分支，提供額外警告
  if (totalDescendants > 50) {
    ElMessageBox.alert(
      `您要删除的"${data.name}"包含 ${totalDescendants} 个子项，这是一个非常大的操作。\n\n建议您先使用“编辑”功能检查数据，或者先删除部分子项再考虑整体删除。`,
      '大量数据删除警告',
      {
        type: 'warning',
        confirmButtonText: '我已知晓',
        callback: () => {
          // 用户确认后继续执行正常的删除流程
          performDelete()
        }
      }
    )
    return
  }
  
  // 正常删除流程
  performDelete()
  
  function performDelete() {
    // 根据是否有子项生成不同的警告信息
    let warningMessage: string
    let confirmButtonText: string
    
    if (hasChildren) {
      if (totalDescendants === childrenCount) {
        // 只有直接子项，没有孙子项
        warningMessage = `
          <div style="text-align: left;">
            <p style="margin: 10px 0; font-weight: bold; color: #E6A23C;">⚠️ 删除警告</p>
            <p style="margin: 8px 0;">您即将删除 "<strong>${data.name}</strong>" 及其下属的 <strong style="color: #F56C6C;">${childrenCount}</strong> 个子项：</p>
            <ul style="margin: 8px 0 8px 20px; color: #666;">
              ${data.children!.slice(0, 3).map(child => `<li>${child.name} [${getTypeLabel(child.type)}]</li>`).join('')}
              ${childrenCount > 3 ? `<li style="color: #909399;">...还有 ${childrenCount - 3} 个项目</li>` : ''}
            </ul>
            <p style="margin: 8px 0; color: #F56C6C; font-weight: bold;">此操作不可恢复，请谨慎操作！</p>
          </div>
        `
        confirmButtonText = `确定删除 (${childrenCount + 1} 项)`
      } else {
        // 有多层子孙项
        warningMessage = `
          <div style="text-align: left;">
            <p style="margin: 10px 0; font-weight: bold; color: #E6A23C;">⚠️ 危险操作警告</p>
            <p style="margin: 8px 0;">您即将删除 "<strong>${data.name}</strong>" 及其下属的所有项目：</p>
            <ul style="margin: 8px 0 8px 20px; color: #666;">
              <li>直接子项: <strong>${childrenCount}</strong> 个</li>
              <li>所有子孙项: <strong style="color: #F56C6C;">${totalDescendants}</strong> 个</li>
            </ul>
            <p style="margin: 8px 0; color: #F56C6C; font-weight: bold;">这将删除整个分支结构，此操作不可恢复！</p>
            <p style="margin: 8px 0; color: #909399; font-size: 12px;">请确认您真的要执行此删除操作。</p>
          </div>
        `
        confirmButtonText = `确认删除 (${totalDescendants + 1} 项)`
      }
    } else {
      // 没有子项的简单删除
      warningMessage = `
        <div style="text-align: left;">
          <p style="margin: 10px 0;">确定要删除 "<strong>${data.name}</strong>" 吗？</p>
          <p style="margin: 8px 0; color: #909399; font-size: 12px;">此操作不可恢复。</p>
        </div>
      `
      confirmButtonText = '确定删除'
    }
    
    ElMessageBox.confirm(warningMessage, '删除确认', {
      confirmButtonText,
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
      customClass: 'delete-confirm-dialog',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          // 显示删除进度
          instance.confirmButtonText = '删除中...'
          instance.confirmButtonLoading = true
          
          // 执行删除
          deleteNode(data.id, data.name).finally(() => {
            instance.confirmButtonLoading = false
            done()
          })
        } else {
          done()
        }
      }
    }).catch(() => {
      // 用户取消操作
      console.log(`用户取消删除操作 - 节点: ${data.name} (ID: ${data.id})`)
    })
  }
}




// 刷新地点位置数据
const refreshLocationData = async () => {
  if (currentTenantId.value) {
    await loadLocationData()
  }
}


// 切换模式
const toggleMode = () => {
  mode.value = mode.value === 'manage' ? 'select' : 'manage'
}

// 暴露方法
defineExpose({
  openDialog,
  loadLocationData,
  refreshLocationData,
  getCurrentTenantId: () => currentTenantId.value,
  getLocationTree: () => fullLocationTree.value,
  isDialogVisible: () => dialogVisible.value,
  closeDialog: () => { dialogVisible.value = false }
})
</script>

<style scoped>
.location-manage-container {
    position: relative;
    padding-top: 0;
  max-height: 600px;
}

.location-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 4px 0;
  padding-right: 180px; /* 为右侧按钮预留空间 */
  position: relative; /* 为绝对定位的子元素提供参考 */
}

.node-icon {
  margin-right: 8px;
  color: #409eff;
}

.node-label {
  font-weight: 500;
}

.node-type {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

.node-actions {
  display: flex;
  gap: 6px;
  opacity: 0;
  transition: opacity 0.3s ease;
  position: absolute; /* 绝对定位，不占据文档流空间 */
  right: 8px; /* 固定在右侧 */
  top: 50%; /* 垂直居中 */
  transform: translateY(-50%); /* 垂直居中对齐 */
}

.tree-node:hover .node-actions {
  opacity: 1;
}

.node-actions .el-button {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  min-width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid transparent;
  transition: all 0.2s ease;
}

.node-actions .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.node-actions .el-button--primary {
  background: linear-gradient(135deg, #409eff, #66b3ff);
  border-color: #409eff;
}

.node-actions .el-button--primary:hover {
  background: linear-gradient(135deg, #337ecc, #409eff);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.node-actions .el-button--info {
  background: linear-gradient(135deg, #909399, #b1b3b8);
  border-color: #909399;
  color: white;
}

.node-actions .el-button--info:hover {
  background: linear-gradient(135deg, #73767a, #909399);
  box-shadow: 0 2px 8px rgba(144, 147, 153, 0.3);
}

.node-actions .el-button--success {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  border-color: #67c23a;
}

.node-actions .el-button--success:hover {
  background: linear-gradient(135deg, #529b2e, #67c23a);
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.node-actions .el-button--danger {
  background: linear-gradient(135deg, #f56c6c, #f78989);
  border-color: #f56c6c;
}

.node-actions .el-button--danger:hover {
  background: linear-gradient(135deg, #dd6161, #f56c6c);
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
}

.node-actions .el-button--danger.delete-btn {
  position: relative;
  overflow: hidden;
}

.node-actions .el-button--danger.delete-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.4);
}

.node-actions .el-button--danger.delete-btn.is-loading {
  background: linear-gradient(135deg, #f19999, #f5b3b3);
  cursor: wait;
  pointer-events: none;
}

.node-actions .el-icon {
  font-size: 12px;
}

.search-tip-icon {
  color: #909399;
}

.search-tip-icon:hover {
  color: #409eff;
}

.suggestion-tag:hover {
  background-color: #409eff;
  color: white;
}

.selection-info {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
}

.selected-items {
  background: white;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.binding-actions {
  text-align: center;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

/* 删除确认对话框样式 */
:deep(.delete-confirm-dialog) {
  .el-message-box__header {
    background: linear-gradient(135deg, #fff2e8, #fef7f0);
    border-bottom: 1px solid #f5dab1;
  }
  
  .el-message-box__title {
    color: #e6a23c;
    font-weight: bold;
  }
  
  .el-message-box__content {
    padding: 20px;
  }
  
  .el-message-box__message {
    font-size: 14px;
    line-height: 1.5;
  }
  
  .el-button--primary {
    background: linear-gradient(135deg, #f56c6c, #f78989);
    border-color: #f56c6c;
  }
  
  .el-button--primary:hover {
    background: linear-gradient(135deg, #dd6161, #f56c6c);
    box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
  }
}

/* 详情对话框样式 */
.detail-dialog .el-dialog__body {
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.detail-content {
  font-size: 14px;
}

.detail-section {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
}

.title-icon {
  margin-right: 8px;
  color: #409eff;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.detail-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 12px;
}

.detail-value {
  color: #303133;
  font-weight: 500;
}

.detail-value.primary {
  color: #409eff;
  font-size: 16px;
  font-weight: bold;
}

.detail-tag {
  font-weight: 500;
}

.children-list {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.child-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background: white;
  border-radius: 6px;
  margin-bottom: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.child-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.child-item:last-child {
  margin-bottom: 0;
}

.child-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.child-icon {
  margin-right: 8px;
  font-size: 16px;
}

.child-name {
  font-weight: 500;
  color: #303133;
  margin-right: 12px;
}

.child-type-tag {
  font-size: 12px;
}

.child-actions {
  flex-shrink: 0;
}

.no-children {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.detail-dialog-footer {
  text-align: right;
}

/* 租户信息卡片样式 */
.tenant-info-section {
  margin-bottom: 16px;
}

.info-card {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
  font-size: 13px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #666;
  font-weight: 500;
  min-width: 60px;
  margin-right: 8px;
}

.info-value {
  flex: 1;
}

/* 编辑对话框样式 */
.edit-dialog .el-dialog__body {
  padding: 20px;
  max-height: 500px;
  overflow-y: auto;
}

.edit-form {
  font-size: 14px;
}

.form-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.form-section:last-child {
  margin-bottom: 0;
}

.form-section .section-title {
  display: flex;
  align-items: center;
  font-size: 15px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e6e8eb;
}

.form-section .section-title::before {
  content: '';
  width: 3px;
  height: 16px;
  background: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.edit-form .el-form-item {
  margin-bottom: 18px;
}

.edit-form .el-form-item__label {
  color: #606266;
  font-weight: 500;
}

.edit-form .el-input,
.edit-form .el-select {
  width: 100%;
}

.edit-form .el-input__inner {
  border-radius: 4px;
  transition: all 0.2s ease;
}

.edit-form .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.edit-dialog-footer {
  text-align: right;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.edit-dialog-footer .el-button {
  min-width: 80px;
  padding: 8px 20px;
}

.edit-dialog-footer .el-button--primary {
  background: linear-gradient(135deg, #409eff, #66b3ff);
  border-color: #409eff;
}

.edit-dialog-footer .el-button--primary:hover {
  background: linear-gradient(135deg, #337ecc, #409eff);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

/* 只读输入框样式 */
.edit-form .el-input.is-disabled .el-input__inner,
.edit-form .el-input__inner[readonly] {
  background-color: #f8f9fa;
  border-color: #e9ecef;
  color: #6c757d;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-dialog {
    width: 90% !important;
    margin: 0 auto;
  }
  
  .form-section {
    padding: 12px;
  }
  
  .edit-form .el-form-item__label {
    font-size: 13px;
  }
}
</style>